package cn.com.yusys.yusp.admin.service;

import cn.com.yusys.yusp.admin.Utils.IDUtils;
import cn.com.yusys.yusp.admin.Utils.Result;
import cn.com.yusys.yusp.admin.Utils.ResultUtils;
import cn.com.yusys.yusp.admin.domain.WcrmMarketActivity;
import cn.com.yusys.yusp.admin.repository.mapper.WcrmMarketActivityMapper;
import cn.com.yusys.yusp.commons.mapper.CommonMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.util.DateUtil;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 营销活动表(WcrmMarketActivity)表服务实现类
 *
 * @author pig4cloud
 * @since 2021-06-24 10:24:09
 */
@Service("wcrmMarketActivityService")
public class WcrmMarketActivityService extends CommonService {

    private static Logger logger = LoggerFactory.getLogger(WcrmMarketActivityService.class);
    @Resource
    private WcrmMarketActivityMapper wcrmMarketActivityMapper;

    @Autowired
    private UserProviderService providerService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public WcrmMarketActivity queryById(String id) {
        return this.wcrmMarketActivityMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    public List<WcrmMarketActivity> queryAllByLimit(int offset, int limit) {
        return this.wcrmMarketActivityMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param wcrmMarketActivity 实例对象
     * @return 实例对象
     */
    public WcrmMarketActivity insert(WcrmMarketActivity wcrmMarketActivity) {
        this.wcrmMarketActivityMapper.insert(wcrmMarketActivity);
        return wcrmMarketActivity;
    }

    /**
     * 修改数据
     *
     * @param wcrmMarketActivity 实例对象
     * @return 实例对象
     */
    public WcrmMarketActivity update(WcrmMarketActivity wcrmMarketActivity) {
        this.wcrmMarketActivityMapper.update(wcrmMarketActivity);
        return this.queryById(wcrmMarketActivity.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(String id) {
        return this.wcrmMarketActivityMapper.deleteById(id) > 0;
    }


    @Override
    protected CommonMapper getMapper() {
        return null;
    }


    public Object queryTableData(QueryModel queryModel) {

        String marketName = (String) queryModel.getCondition().get("marketName");
        String actSource = (String) queryModel.getCondition().get("actSource");
        String createOrg = (String) queryModel.getCondition().get("createOrg");
        String roleId = (String) queryModel.getCondition().get("roleId");
        String orgId = (String) queryModel.getCondition().get("orgId");
        String userId = (String) queryModel.getCondition().get("userId");

        PageHelper.startPage(queryModel.getPage(), queryModel.getSize());
        List<Map<String, Object>> list = null;
        //分行行长查询显示其所有属于其所属的机构下客户
        if (orgId.equals("070667XN0") || orgId.equals("070667XN1") || orgId.equals("070667860") || orgId.equals("070667XN3")) {
            queryModel.getCondition().put("roleLevel", "1");
            list = wcrmMarketActivityMapper.queryTableData(queryModel);
            return list;
        }
        //查询支行下所属的所有客户经理的用户 Sub-branch Manager
        //客户经理
        if (roleId.equals("R0001") || roleId.equals("R0002") || roleId.equals("R0009")) {
            queryModel.getCondition().put("roleLevel", "2");
            queryModel.getCondition().put("isManager",true);
            list = wcrmMarketActivityMapper.queryTableData(queryModel);
        }
        //查询所有用户
        //总行管理员
        if (roleId.equals("R0008") || roleId.equals("R0007") || roleId.equals("R001")) {
            queryModel.getCondition().put("roleLevel", "0");
            list = wcrmMarketActivityMapper.queryTableData(queryModel);
        }
        //支行行长查询，显示其机构下所有客户
        if (roleId.equals("R0006") || roleId.equals("R0005") || roleId.equals("R0003") || roleId.equals("R0004")) {
            queryModel.getCondition().put("roleLevel", "2");
            list = wcrmMarketActivityMapper.queryTableData(queryModel);
        }
        PageHelper.clearPage();
        return list;

    }

    public Integer saveMarketActivity(Map queryModel) {
        int i = 0;
        if (queryModel.get("id") == null || "".equals(queryModel.get("id"))) {
            //新增
            queryModel.put("id", IDUtils.getGuid());
            queryModel.put("actId", IDUtils.getGuid());
            queryModel.put("createUser", providerService.getUserCode());
            queryModel.put("createTime", DateUtil.formatDateTimeByDef());
            queryModel.put("actStatus", "1");
            queryModel.put("upAct", "0");
            if (queryModel.get("orgId").equals("070667XN0") || queryModel.get("orgId").equals("070667XN1") || queryModel.get("orgId").equals("070667860") || queryModel.get("orgId").equals("070667XN3")) {
                queryModel.put("actSource", "1");
            }
            //支行行长创建，显示其机构下所有客户
            if (queryModel.get("roleId").equals("R0006") || queryModel.get("roleId").equals("R0005") || queryModel.get("roleId").equals("R0003") || queryModel.get("roleId").equals("R0004")) {
                queryModel.put("actSource", "2");
            }
            //查询支行下所属的所有客户经理的用户 Sub-branch Manager
//            //客户经理
            if (queryModel.get("roleId").equals("R0001") || queryModel.get("roleId").equals("R0002") || queryModel.get("roleId").equals("R0009")) {
                queryModel.put("actSource", "1");
            }
            //查询所有用户
            //总行管理员
            if (queryModel.get("roleId").equals("R0008") || queryModel.get("roleId").equals("R0007") || queryModel.get("roleId").equals("R001")) {
                queryModel.put("actSource", "1");
            }

            i = wcrmMarketActivityMapper.insertMarketActivity(queryModel);
        } else {
//			List<Map<String, Object>> list = wcrmMarketActivityMapper.selectMarketActivityById(queryModel);
            //更新
            queryModel.put("lastUpdateUser", providerService.getUserCode());
            queryModel.put("lastUpdateTime", DateUtil.formatDateTimeByDef());
            i = wcrmMarketActivityMapper.updateMarketActivity(queryModel);
        }
        return i;
    }

    /**
     * 删除营销活动的业务逻辑
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public Result<String> deletebatch(String ids) {
        if (StringUtils.isEmpty(ids)) return ResultUtils.error("参数不能为空");
        try {
            String[] split = ids.split(",");
            wcrmMarketActivityMapper.deleteMarketActivityById(split);
            return ResultUtils.success("数据删除成功");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            return ResultUtils.error("系统错误, 请联系管理员");
        }
    }

    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Result<String> saveIssus(QueryModel queryModel) {
        int i = 0;
        //查询所有非叶子节点ID并进行过滤
        List<Map<String, Object>> list = wcrmMarketActivityMapper.selectNotLeafNodeId();
        List<String> list_orgId = new ArrayList<>();
        for (int j = 0; j < list.size(); j++) {
            list_orgId.add(list.get(j).get("orgId").toString());
        }
        HashMap<String, String> execTopy = new HashMap<>();
        if (queryModel.getCondition().get("execTopyNum") != null && !"".equals(queryModel.getCondition().get("execTopyNum").toString())) {
            List<String> execTopyNum = Arrays.asList(queryModel.getCondition().get("execTopyNum").toString().split(","));
            List<String> execTopyName = Arrays.asList(queryModel.getCondition().get("execTopyName").toString().split(","));

            for (int j = 0; j < execTopyNum.size(); j++) {
                execTopy.put(execTopyNum.get(j), execTopyName.get(j));
            }

            Map<String, String> collect = execTopy.entrySet().stream().filter(s -> !list_orgId.contains(s.getKey())).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

            WcrmMarketActivity wcrmMarketActivity = wcrmMarketActivityMapper.queryById(queryModel.getCondition().get("id").toString());
            WcrmMarketActivity wcrmMarketActivity1 = new WcrmMarketActivity();
            wcrmMarketActivity1.setId(queryModel.getCondition().get("id").toString());
            wcrmMarketActivity1.setActStatus("2");
            wcrmMarketActivityMapper.update(wcrmMarketActivity1);
            List<WcrmMarketActivity> wcrmMarketActivities = new ArrayList<>();
            for (Map.Entry<String, String> entry : collect.entrySet()) {
                String guid = IDUtils.getGuid();
                WcrmMarketActivity wcrmMarketActivityCopy = new WcrmMarketActivity();
                BeanUtils.copyProperties(wcrmMarketActivity, wcrmMarketActivityCopy);
                wcrmMarketActivityCopy.setId(guid);
                wcrmMarketActivityCopy.setActId(guid);
                wcrmMarketActivityCopy.setActContent(wcrmMarketActivity.getActContent());
                wcrmMarketActivityCopy.setMarketName(wcrmMarketActivityCopy.getMarketName() + "-" + entry.getValue());
                wcrmMarketActivityCopy.setUpAct(wcrmMarketActivity.getActId());
                wcrmMarketActivityCopy.setActStatus("1");
                //总行下发
                wcrmMarketActivityCopy.setActSource("1");
                wcrmMarketActivityCopy.setIssusOrg(entry.getKey());
                wcrmMarketActivityCopy.setLastUpdateUser(providerService.getUserCode());
                wcrmMarketActivityCopy.setLastUpdateUserName(queryModel.getCondition().get("userName").toString());
                wcrmMarketActivityCopy.setLastUpdateTime(LocalDateTime.now());
                wcrmMarketActivityCopy.setCreateUser(providerService.getUserCode());
                wcrmMarketActivityCopy.setCreateUserName(queryModel.getCondition().get("userName").toString());
                wcrmMarketActivities.add(wcrmMarketActivityCopy);
            }

            //insert条数=数组的数量
            int i1 = wcrmMarketActivityMapper.insertBatch(wcrmMarketActivities);
            if (collect.size() == i1) {
                return ResultUtils.success("数据下发成功");
            } else {
                return ResultUtils.error("系统错误, 数据已回滚");
            }
        } else {
            return ResultUtils.error("系统错误, 请联系管理员");
        }

    }

    public Result<String> saveIssusMgr(QueryModel queryModel) {
        if (queryModel.getCondition().get("userID") != null && !"".equals(queryModel.getCondition().get("userID").toString())) {
            String userID = String.valueOf(queryModel.getCondition().get("userID"));
            String id = String.valueOf(queryModel.getCondition().get("id").toString());

            Map<String, Object> map = wcrmMarketActivityMapper.selectSmUser(userID);

            String userId = String.valueOf(map.get("userid"));
            String userName = String.valueOf(map.get("username"));
            String orgId = String.valueOf(map.get("orgid"));

            WcrmMarketActivity wcrmMarketActivity = wcrmMarketActivityMapper.queryById(id);
            WcrmMarketActivity wcrmMarketActivity1 = new WcrmMarketActivity();
            wcrmMarketActivity1.setId(id);
            wcrmMarketActivity1.setActStatus("2");
            wcrmMarketActivityMapper.update(wcrmMarketActivity1);
            List<WcrmMarketActivity> wcrmMarketActivities = new ArrayList<>();
            String guid = IDUtils.getGuid();
            WcrmMarketActivity wcrmMarketActivityCopy = new WcrmMarketActivity();
            BeanUtils.copyProperties(wcrmMarketActivity, wcrmMarketActivityCopy);
            wcrmMarketActivityCopy.setId(guid);
            wcrmMarketActivityCopy.setActId(guid);
            //支行创建
            wcrmMarketActivityCopy.setActSource("2");
            wcrmMarketActivityCopy.setActContent(wcrmMarketActivity.getActContent());
            wcrmMarketActivityCopy.setMarketName(wcrmMarketActivityCopy.getMarketName() + "-" + userName);
            wcrmMarketActivityCopy.setUpAct(wcrmMarketActivity.getActId());
            wcrmMarketActivityCopy.setActStatus("1");
            wcrmMarketActivityCopy.setActLeader(userID);
            wcrmMarketActivityCopy.setActLeaderName(userName);
            wcrmMarketActivityCopy.setIssusOrg(orgId);
            wcrmMarketActivityCopy.setLastUpdateUser(providerService.getUserCode());
            wcrmMarketActivityCopy.setLastUpdateUserName(queryModel.getCondition().get("userName").toString());
            wcrmMarketActivityCopy.setLastUpdateTime(LocalDateTime.now());
            wcrmMarketActivityCopy.setCreateUser(providerService.getUserCode());
            wcrmMarketActivityCopy.setCreateUserName(queryModel.getCondition().get("userName").toString());
            wcrmMarketActivityCopy.setCreateTime(LocalDateTime.now());
            wcrmMarketActivities.add(wcrmMarketActivityCopy);
            //insert条数=数组的数量
            int i1 = wcrmMarketActivityMapper.insertBatchMgr(wcrmMarketActivities);
            if (i1 > 0) {
                return ResultUtils.success("数据下发成功");
            } else {
                return ResultUtils.error("系统错误, 数据已回滚");
            }
        } else {
            return ResultUtils.error("系统错误, 请联系管理员");
        }
    }

//    /**
//     * 从listA里删除listB里有的数据
//     * @param listA
//     * @param listB
//     * @return
//     */
//    public static List<String> listrem(List<String> listA,List<String> listB){
//        for (Iterator<String> itA = listA.iterator(); itA.hasNext();)
//        {
//            String temp = itA.next();
//            // itA.next() 只能在外层循环里面调用1次
//            for (int i = 0; i < listB.size(); i++)
//            {
//                if (temp.equals(listB.get(i)))
//                // 你不该在这里多次调用itA.next()的
//                {
//                    itA.remove();
//                }
//            }
//        }
//        return listA;
//    }
}